package com.loong.musicdemo.util.deleteutil;

import android.os.Environment;

import com.loong.musicdemo.model.LocalPlay;

import org.litepal.LitePal;

import java.io.File;
import java.util.Objects;

/**
 * 删除音乐工具类
 */
public class DeleteMusicUtil {
    /**
     * 删除所有本地音乐信息
     * <p>
     * 删除结果
     */
    public static boolean deleteAllMusics() {
        //删除本地文件
        String directory = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getPath() + "/mymusic/";

        File file;
        file = new File(directory);
        if (!file.exists() || !file.isDirectory()){
            return false;
        }
        for (File listFile : Objects.requireNonNull(file.listFiles())) {
            listFile.delete();//删除目录下文件
        }
        boolean b = file.delete();
        if (b)
            //删除数据库
            LitePal.deleteAll(LocalPlay.class);//如果本地文件删除成功,则删除...
        return b;
    }

    /**
     * 根据歌曲的id删除音乐
     *
     * @param id 歌曲id
     */
    public static boolean deleteMusicById(String id) {
        //删除数据库中数据
        LitePal.deleteAll(LocalPlay.class, "songId = ?", id);
        //删除音乐文件
        //删除本地文件
        String directory = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getPath() + "/mymusic/";

        File file;
        file = new File(directory + id + ".mp3");
        return file.delete();
    }
}
